package com.dq.demos.web.utils;

import ch.qos.logback.core.util.FileUtil;
import cn.hutool.http.HttpUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.*;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletOutputStream;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;

import static org.glassfish.jersey.client.ClientProperties.CONNECT_TIMEOUT;
import static org.glassfish.jersey.client.ClientProperties.READ_TIMEOUT;

/**
 * <p>HTTP工具类</p>
 *
 * @author Administrator
 * @date 2022-07-05
 */
public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get请求
     *
     * @param httpurl
     * @return
     */
    public static String doGet(String httpurl, Map<String, String> map) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            StringBuilder urlc = new StringBuilder();
            for (String key : map.keySet()) {
                urlc.append(key + "=" + map.get(key)+"&");
            }
            urlc.deleteCharAt(urlc.length()-1);
            httpurl += "?" + urlc.toString();
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    /**
     * get请求
     *
     * @param httpurl
     * @return
     */
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    /**
     * get请求
     *
     * @param urlStr
     * @return
     */
    public static ByteArrayOutputStream doGetInputStream(String urlStr) throws Exception {
        InputStream content = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        ByteArrayOutputStream baos = null;
        try {
            // 创建httpclient对象
            httpClient = HttpClients.createDefault();
            // 创建请求对象
            HttpGet httpGet = new HttpGet(urlStr);
            // 发送请求，接收响应
            response = httpClient.execute(httpGet);
            // 获取状态码
            int statusCode = response.getStatusLine().getStatusCode();
            response.addHeader("Access-Control-Allow-Origin","*");
            response.addHeader("Access-Control-Expose-Headers","*");
            response.addHeader("Content-disposition","attachment;filename=" + urlStr);
            // 获取响应数据
            HttpEntity entity = response.getEntity();
            content = entity.getContent();
            baos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];        //缓冲区
            while ((len = content.read(buffer)) != -1) {   //将接受的数据写入缓冲区数组buffer
                baos.write(buffer, 0, len);          //将缓冲区buffer写入byte数组输出流
            }
            int read = content.read();
            String[] split = urlStr.split("/");
            File file = new File("D:\\dq_zlbp\\" + split[split.length - 1]);
            createFile(file);
            copyInputStreamToFile(content, file);
            IOUtils.write(baos.toByteArray(), baos);
        } catch (Exception e) {
            throw new Exception("http请求失败:" + e.getMessage());
        } finally {
            // 关闭资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
        return baos;
    }

    /**
     * 流输出到文件的方法
     */
    private static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024000];

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }
    }

    public static void createFile(File file) throws Exception {
        if (file.exists()) {
            System.out.println("File exists");
        } else {
            System.out.println("File not exists, create it ...");
            //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
            if (!file.getParentFile().exists()) {
                System.out.println("not exists");
                //创建上级目录
                file.getParentFile().mkdirs();
            }
            try {
                //在上级目录里创建文件
                file.createNewFile();
                // Thread.sleep(2);
            } catch (IOException e) {
                throw new Exception(e.getMessage());
            }
        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        OutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//解决乱码
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = conn.getOutputStream();
            out.write(param.getBytes("UTF-8"));
            out.flush();
            int code = conn.getResponseCode();
            logger.error("返回的code" + code);
            if (code == 200) {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line + "\n";
                }
            }
        } catch (Exception e) {
            result = "请求http失败" + e.getMessage();
            logger.error(result);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("--->HTTP请求输入输出流关闭异常：【"+ex.getMessage()+"】");
            }
        }
        return result;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url) {
        OutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//解决乱码
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = conn.getOutputStream();
            out.write(null);
            out.flush();
            int code = conn.getResponseCode();
            logger.error("返回的code" + code);
            if (code == 200) {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line + "\n";
                }
            }
            String[] split = url.split("/");
            File file = new File("D:\\dq_zlbp\\" + split[split.length - 1]);
            HttpUtil.downloadFile(url, file);
        } catch (Exception e) {
            result = "请求http失败" + e.getMessage();
            logger.error(result);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("--->HTTP请求输入输出流关闭异常：【"+ex.getMessage()+"】");
            }
        }
        return result;
    }
    /**
     * 向指定 URL 带head发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendHeadPost(String url, String param, Map<String, String> heads) {
        OutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
//			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//解决乱码
            if (heads != null && heads.size() > 0) {
                for (String key : heads.keySet()) {
                    String value = heads.get(key);
                    conn.setRequestProperty(key, value);
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            out = conn.getOutputStream();
            out.write(param.getBytes("UTF-8"));
            out.flush();
            int code = conn.getResponseCode();
            if (code == 200) {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;

                while ((line = in.readLine()) != null) {
                    result += line + "\n";
                }
            }
        } catch (Exception e) {
            result = "请求http失败" + e.getMessage();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("--->HTTP请求输入输出流关闭异常：【"+ex.getMessage()+"】");
            }
        }
        return result;
    }

    public static String sendHeadPostss(String url, Map<String, String> heads) {
        OutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
//			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//解决乱码
            if (heads != null && heads.size() > 0) {
                for (String key : heads.keySet()) {
                    String value = heads.get(key);
                    conn.setRequestProperty(key, value);
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = conn.getOutputStream();
            out.flush();
            int code = conn.getResponseCode();
            if (code == 200) {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;

                while ((line = in.readLine()) != null) {
                    result += line + "\n";
                }
            }
        } catch (Exception e) {
            result = "请求http失败" + e.getMessage();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("--->HTTP请求输入输出流关闭异常：【"+ex.getMessage()+"】");
            }
        }
        return result;
    }


    /**
     * 此方法仅供参考，第三方系统可采用自己的方式调用http接口【OA消息发送的http】
     *
     * @param path 请求路径
     * @param data 请求参数
     * @return
     */
    public static String oapost(String path, Map<String, String> params, Map<String, String> data) {
        try {
            String str = "";
//            if (params != null) {
//                StringBuilder stringBuilder = new StringBuilder("?");
//                for (Map.Entry<String, String> entry : params.entrySet()) {
//                    stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
//                }
//                if (stringBuilder.length() > 1)
//                    path += stringBuilder.substring(0, stringBuilder.length() - 1);
//            }
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            PrintWriter out = null;
            // 请求参数 编码为 utf-8
            //请求方式
            conn.setRequestMethod("POST");
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            if (data != null)
                for (Map.Entry<String, String> entry : data.entrySet())
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (params != null)
                out.write(mapToStr(params));
            //缓冲数据
            out.flush();
            out.close();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String result = "";
            while ((str = br.readLine()) != null) {
                result = str;
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将Map转换成字符串参数，用于POST GET 请求
     *
     * @param map
     * @return
     */
    public static String mapToStr(Map<String, String> map) {
        StringBuilder stringBuilder = new StringBuilder();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                stringBuilder.append(entry.getKey());
                if (entry.getValue() != null)
                    stringBuilder.append("=").append(entry.getValue());
                stringBuilder.append("&");
            }
        }
        if (stringBuilder.length() > 0)
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        return null;
    }


    /**
     * post请求，支持https请求
     *
     * @param url         需要请求的网关路径
     * @param sendData    请求时需要传入的参数
     * @param urlencode   url的编码格式
     * @param connTimeOut 链接超时时间
     * @param readTimeOut 读取超时时间
     * @param contentType 请求头部  固定输入"application/x-www-form-urlencoded;charset="+urlencode
     * @param header      输入null
     * @return
     */
    public static String sendAndRcvHttpPostBase(String url, String sendData, String urlencode, int connTimeOut, int readTimeOut, String contentType, Map<String, String> header) {
        Long curTime = System.currentTimeMillis();
        String result = "";
        BufferedReader in = null;
        DataOutputStream out = null;
        int code = 999;
        HttpsURLConnection httpsConn = null;
        HttpURLConnection httpConn = null;
        try {
            URL myURL = new URL(url);
            if (url.startsWith("https://")) {
                httpsConn = (HttpsURLConnection) myURL.openConnection();
                TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return null;
                            }

                            public void checkClientTrusted(
                                    java.security.cert.X509Certificate[] certs, String authType) {
                            }

                            public void checkServerTrusted(
                                    java.security.cert.X509Certificate[] certs, String authType) {
                            }
                        }
                };
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                httpsConn.setSSLSocketFactory(sc.getSocketFactory());
                HostnameVerifier hv = new HostnameVerifier() {
                    @Override
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                };
                httpsConn.setHostnameVerifier(hv);

                httpsConn.setRequestProperty("Accept-Charset", urlencode);
                httpsConn.setRequestProperty("User-Agent", "java HttpsURLConnection");
                if (header != null) {
                    for (String key : header.keySet()) {
                        httpsConn.setRequestProperty(key, (String) header.get(key));
                    }
                }
                httpsConn.setRequestMethod("POST");
                httpsConn.setUseCaches(false);
                httpsConn.setRequestProperty("Content-Type", contentType);
                httpsConn.setConnectTimeout(connTimeOut);
                httpsConn.setReadTimeout(readTimeOut);
                httpsConn.setDoInput(true);
                httpsConn.setInstanceFollowRedirects(true);
                if (sendData != null) {
                    httpsConn.setDoOutput(true);
                    // 获取URLConnection对象对应的输出流
                    out = new DataOutputStream(httpsConn.getOutputStream());
                    // 发送请求参数
                    out.write(sendData.getBytes(urlencode));
                    // flush输出流的缓冲
                    out.flush();
                    out.close();
                }
                // 取得该连接的输入流，以读取响应内容
                in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), urlencode));
                code = httpsConn.getResponseCode();
            } else {
                httpConn = (HttpURLConnection) myURL.openConnection();
                httpConn.setRequestProperty("Accept-Charset", urlencode);
                httpConn.setRequestProperty("user-agent", "java HttpURLConnection");
                if (header != null) {
                    for (String key : header.keySet()) {
                        httpConn.setRequestProperty(key, (String) header.get(key));
                    }
                }
                httpConn.setRequestMethod("POST");
                httpConn.setUseCaches(false);
                httpConn.setRequestProperty("Content-Type", contentType);
                httpConn.setConnectTimeout(connTimeOut);
                httpConn.setReadTimeout(readTimeOut);
                httpConn.setDoInput(true);
                httpConn.setInstanceFollowRedirects(true);
                if (sendData != null) {
                    httpConn.setDoOutput(true);
                    // 获取URLConnection对象对应的输出流
                    out = new DataOutputStream(httpConn.getOutputStream());
                    // 发送请求参数
                    out.write(sendData.getBytes(urlencode));
                    // flush输出流的缓冲
                    out.flush();
                    out.close();
                }
                // 取得该连接的输入流，以读取响应内容
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), urlencode));
                code = httpConn.getResponseCode();
            }
            if (HttpURLConnection.HTTP_OK == code) {
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                    System.out.println("=====返回结果=====" + line);
                }
                if (result.length() > 2000) {
                    logger.error("http返回结果 !\n" + result.substring(0, 2000) + "...");
                } else {
                    logger.error("http返回结果 !\n" + result);
                }
            } else {
                result = null;
                logger.error("发送代办失败,服务端响应码：" + code);
                throw new Exception("发送代办失败,服务端响应码：" + code);
            }
        } catch (IOException e) {
            logger.error("http通讯失败 !" + e.getMessage());
            result = null;
        } catch (Exception e) {
            logger.error("http通讯失败 !" + e.getMessage());
            result = null;
        } finally {
            logger.error("对方地址：" + url);
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("关闭流失败：" + e.getMessage());
                }
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
            if (httpsConn != null) {
                httpsConn.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
        logger.error("SimpleHttpConnUtil " + curTime + " end for " + (System.currentTimeMillis() - curTime) + "ms");
        return result;
    }


    private static void handlerFile(ZipOutputStream zip, File file, String dir) throws Exception {
        //如果当前的是文件夹，则进行进一步处理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] fileArray = file.listFiles();
            if (fileArray == null) {
                return;
            }
            //将文件夹添加到下一级打包目录
            zip.putNextEntry(new ZipEntry(dir + "/"));
            dir = dir.length() == 0 ? "" : dir + "/";
            //递归将文件夹中的文件打包
            for (File f : fileArray) {
                handlerFile(zip, f, dir + f.getName());
            }
        } else {
            //当前的是文件，打包处理
            //创建文件缓冲输入流，读取目标文件
            FileInputStream fin = new FileInputStream(file);
            ZipEntry entry = new ZipEntry(dir);
            zip.putNextEntry(entry);
            int length;
            byte[] buffer = new byte[1024];
            while((length = fin.read(buffer)) > 0) {
                zip.write(buffer, 0, length);
            }
            zip.flush();
            fin.close();
            zip.closeEntry();
        }
    }
    //返回二进制压缩包文件流
    private static byte[] createZip(String sourceFilePath) throws Exception{
        //1、创建字节数组输出流，用于返回压缩后的输出流字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //2、创建压缩输出流
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //将目标文件打包成zip导出
        File file = new File(sourceFilePath);
        handlerFile(zip, file,"");
        //IOUtils.closeQuietly(zip);
        zip.close();
        return outputStream.toByteArray();
    }
    //删除文件
    private static void deleteFile(File file) {
        if (file.exists()) {//判断文件是否存在
            if (file.isFile()) {//判断是否是文件
                file.delete();//删除文件
            } else if (file.isDirectory()) {//否则如果它是一个目录
                File[] files = file.listFiles();//声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) {//遍历目录下所有的文件
                    deleteFile(files[i]);//把每个文件用这个方法进行迭代
                }
                file.delete();//删除文件夹
            }
        } else {
            System.out.println("所删除的文件不存在");
        }
    }
}
